package ln.javatest.day01.demo01;
/*
演示jdbc工具类
*/

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBCDemo05 {
    public static void main(String[] args) {
        //成员变量，需要new对象才能使用
        //静态方法，类名直接点就可以用
        JDBCDemo05 jd4 = new JDBCDemo05();
        List<Student> list1 =jd4.findAll();
        System.out.println(list1);
    }

    //查询所有Student对象
    public List<Student> findAll(){  //成员变量，需要new对象才能使用
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        List<Student> list = null;
        try {
            /*//注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            conn = DriverManager.getConnection("jdbc:mysql:///db1", "root", "123456");*/
            conn = JDBCUtils.getConnection();
            //定义sql
            String sql = "Select * from Student";
            //获取执行sql的对象
            stat = conn.createStatement();
            //执行sql
            rs = stat.executeQuery(sql);
            //遍历结果集，封装对象，装载集合
            Student s = null;
            list = new ArrayList<>();
            while(rs.next()){
                //获取数据
                int id = rs.getInt(1);
                String namee = rs.getString("namee");
                int sorce = rs.getInt(1);
                String sex = rs.getString("sex");
                int age = rs.getInt(1);
                //创建Student对象,并赋值
                s = new Student();
                s.setId(id);
                s.setNamee(namee);
                s.setSorce(sorce);
                s.setSex(sex);
                s.setAge(age);
                //装载集合
                list.add(s);
            }
        }  catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            /*if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(stat!=null){
                try {
                    stat.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }*/
            JDBCUtils.close(rs,stat,conn);
        }
        return list;
    }
}
